package menu

import (
	"context"
	"github.com/pkg/errors"
	"trusteva/app/rbac/model"

	"trusteva/app/rbac/internal/svc"
	"trusteva/app/rbac/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MenuAddActionLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMenuAddActionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MenuAddActionLogic {
	return &MenuAddActionLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MenuAddActionLogic) MenuAddAction(req *types.MenuAddActionRo) (resp *types.BaseRsp, err error) {
	var menu model.MenuConfig
	if err = l.svcCtx.DB.WithContext(l.ctx).Where("Id=?", req.MenuId).First(&menu).Error; err != nil {
		return nil, errors.Wrap(err, "菜单不存在")
	}

	var action model.ActionConfig
	if err = l.svcCtx.DB.WithContext(l.ctx).Where("Id=?", req.ActionId).First(&action).Error; err != nil {
		return nil, errors.Wrap(err, "功能不存在")
	}

	menu.Actions = menu.Actions.Add(req.ActionId)

	err = l.svcCtx.DB.WithContext(l.ctx).Model(&model.MenuConfig{}).Where("Id=?", req.MenuId).
		Update("Actions", menu.Actions).Error

	return
}
